<?php

class Widget {

	private $id;
	private $name;
	private $description;
	private $hDB;
	private $needsUpdating = false;

  public function __construct($widgetID) {

	$this->hDB =mysql_connect("localhost","root","bing");
	if(!is_resource($this->hDB)) {
	  throw new Exception('Unable to connect to Mysql.');
	}
	
    mysql_select_db("php6",$this->hDB);
	$sql = "SELECT name, description FROM widget WHERE widgetid = $widgetID";
	$rs = mysql_query($sql,$this->hDB);
	if(!is_resource($rs)) {
	  throw new Exception("An error occurred selecting from the database.");
	}
    
	$data =mysql_fetch_array($rs);
	$this->id =$widgetID;
	$this->name = $data['name'];

	$this->description = $data['description'];
  }

  public function getName() {
	return $this->name;
  }

  public function getDescription() {
	return $this->description;
  }

  public function setName($name) {
	$this->name = $name;
	$this->needsUpdating = true;
  }

  public function setDescription($description) {
	$this->description = $description;
	$this->needsUpdation = true;
  }

  public function __destruct() {
	if($this->needsUpdating) {
	
   
    /*$sql ="UPDATE widget SET name = '{$this->name}', description ='{$this->description}' WHERE WidgetID = '{$this->id}'";书中用了pg_escapt_string()函数,不明白. */

	$sql ="UPDATE widget SET ";
	$sql .="name = '{$this->name}',";
	$sql .="description ='{$this->description}'";
	$sql .="WHERE WidgetID = '{$this->id}'";
	$rs = mysql_query($sql,$this->hDB);
	mysql_close($this->hDB);
	}
  }
}
?>
